package com.cn.common.consistenthash;

import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

public class ConsistentHash {

    /**
     * 虚拟节点数
     */
    private final int virtualCount;

    private Md5Hash md5Hash;

    private SortedMap<Long, VirtualNode> ring = new TreeMap<>();

    public ConsistentHash() {
        this.virtualCount = 10;
        this.md5Hash = new Md5Hash();
    }

    public ConsistentHash(int virtualCount, List<Node> phyNodes) {
        this.virtualCount = virtualCount;
        this.md5Hash = new Md5Hash();
        for (Node node : phyNodes) {
            addNode(node);
        }
    }

    public void addNode(Node node) {
        for (int i = 0; i < this.virtualCount; i++) {
            VirtualNode virtualNode = new VirtualNode(node, i);
            ring.put(md5Hash.hash(virtualNode.getKey()), virtualNode);
        }
    }

    public VirtualNode route(String key) {
        long objKey = md5Hash.hash(key);
        SortedMap<Long, VirtualNode> tmpNode = ring.tailMap(objKey);
        Long fromKey;
        if (tmpNode.isEmpty()) {
            fromKey = this.ring.firstKey();
        } else {
            fromKey = tmpNode.firstKey();
        }
        return ring.get(fromKey);
    }


}
